package yxy.game.pm2.command.pack;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.equipdata;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

/** 背包 装备出售 */
@MessageType(proto = Command.EquipSell, classtype = PackageMessage.EquipSellRequest.class)
public class CMD_EquipSell extends Command<PackageMessage.EquipSellRequest> {

	@Override
	public void execute(MessageSource messageSource, PackageMessage.EquipSellRequest request) {
		String playerCode = messageSource.getTag();
		int dataId = request.getDataId();
		int num = request.getNum();

		PackageMessage.EquipSellResponse.Builder response = PackageMessage.EquipSellResponse.newBuilder();

		equipdata _equipdata = DataCenter.getData(dataId, equipdata.class);
		if (_equipdata == null) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		if (num < 0) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		try {
			new CurrencyHandle().cost(playerCode, CCReason.售卖装备, Currency.create(CurrencyType.CT_装备, dataId, num));
		} catch (Exception e) {
			send(messageSource, response, Result.PackItemNumberLack);// 错误码 数量不够
			return;
		}
		Currency back = Currency.create(CurrencyType.CT_钱币, 0, _equipdata.getSellgold() * num);
		new CurrencyHandle().addCurrency(playerCode, CCReason.售卖装备, back);

		try {
			response.setItem(new CurrencyHandle().packItem(Item.get(playerCode, CurrencyType.CT_装备, dataId)));
			response.setSale(new CurrencyHandle().packPoint(back));
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, PackageMessage.EquipSellResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}